const BaseService = require("../base");

class AttrsService extends BaseService {
  async getAttrList({ category1Id, category2Id, category3Id }) {
    const ctx = this.ctx;

    const attrs = await ctx.model.Product.Attrs.find({
      $or: [
        {
          categoryId: category1Id,
          categoryLevel: 1,
        },
        {
          categoryId: category2Id,
          categoryLevel: 2,
        },
        {
          categoryId: category3Id,
          categoryLevel: 3,
        },
      ],
    });

    return this.toId(attrs);
  }

  async saveAttr(attr) {
    const ctx = this.ctx;
    await ctx.model.Product.Attrs.create(attr);
    return null;
  }

  async updateAttr(attr) {
    const ctx = this.ctx;
    const res = await ctx.model.Product.Attrs.findOneAndUpdate({ _id: attr.id, isAdmin: false }, attr, {
      useFindAndModify: false,
    });
    // 如果执行成功。会有返回值
    if (res) return true;
    // 如果执行失败，没有返回值
    return false;
  }

  async removeAttr(id) {
    const ctx = this.ctx;
    const res = await ctx.model.Product.Attrs.deleteOne({ _id: id, isAdmin: false });
    // 如果执行成功。会有返回值
    if (res.deletedCount) return true;
    // 如果执行失败，没有返回值
    return false;
  }
}

module.exports = AttrsService;
